package com.ruoyi.common.core.phone;

import com.ruoyi.common.core.constant.RegexConstant;
import com.ruoyi.common.core.utils.ResetMessageUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.ObjectUtils;

import java.util.regex.Pattern;

/**
 * @Author: Painter
 * @project_name: RuoYi-Cloud
 * @system_login: sunshine
 * @time: 2024/2/23 10:32
 */

/**
 * 手机号码格式校验器
 */
public class MobilePhoneValidator implements ConstraintValidator<MobilePhone, String> {

    // 手机号码的详细描述。
    private String description;


    @Override
    public void initialize(MobilePhone constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        description = constraintAnnotation.description();
    }


    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (ObjectUtils.isEmpty(value)) {
            return true;
        }

        if (value.contains(" ")) {
            String message = String.format("%s，格式错误：不能包含空格", description);
            ResetMessageUtil.reset(context, message);
            return false;
        }

        if (!isMobilePhone(value)) {
            String message = String.format("%s，格式错误", description);
            ResetMessageUtil.reset(context, message);
            return false;
        }

        return true;
    }

    /**
     * 是手机号码
     */
    private boolean isMobilePhone(CharSequence input) {
        Pattern PATTERN = Pattern.compile(RegexConstant.MOBILE_PHONE);
        return PATTERN.matcher(input).matches();
    }

}

